import paho.mqtt.client as mqtt
from mqtt.common.common_topic_request import CommonTopicRequest
from mqtt.common.method_topic_request import MethodTopicRequest
from mqtt.common.common_constant import CommonConstant


class MqttPublish:
    _instance = None  # 类变量，存储唯一的实例

    def __new__(cls, *args, **kwargs):
        # 如果实例不存在，则创建一个新的实例
        if cls._instance is None:
            cls._instance = super(MqttPublish, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, broker_address="192.168.70.229", port=1883):
        if not hasattr(self, "client"):  # 防止重新初始化
            self.broker_address = broker_address  # 公共测试服务器地址
            self.port = port  # MQTT 默认端口
            self.client = mqtt.Client()  # 初始化 MQTT 客户端
            self.client.connect(self.broker_address, self.port)  # 连接到 Broker
            print(f"MQTT Client Initialized: {self.broker_address}:{self.port}")

    def publish(self, gateway_sn, suffix, data):
        payload = CommonTopicRequest(data=data)
        self.client.publish(f"{CommonConstant.TOPIC_PREFIX}{gateway_sn}{suffix}", payload.to_json())

    def publish_with_method(self, gateway_sn, suffix, data, method, wait_reply=True):
        payload = MethodTopicRequest(data=data, method=method)
        self.client.publish(f"{CommonConstant.TOPIC_PREFIX}{gateway_sn}{suffix}", payload.to_json())
        if wait_reply:
            # todo wait replay
            pass

    def stop(self):
        self.client.disconnect()
        print("Disconnected from broker")
